from twisted.internet import reactor
from twisted.python import log
from twisted.web import http, proxy
import sys

DenyHosts = [
    'ad.doubleclick.com',
    'ads.revsci.net',
    'ads.img.globo.com',
    'ads.imguol.com',
]

class BlockingProxyRequest(proxy.ProxyRequest):
    def process(self):
        for host in DenyHosts:
            log.msg('URI=' + self.uri)
            if host in self.uri:
                self.transport.loseConnection()
        proxy.ProxyRequest.process(self)

class BlockingProxy(proxy.Proxy):
    requestFactory = BlockingProxyRequest

class ProxyFactory(http.HTTPFactory):
    protocol = BlockingProxy

def run(port=8080):
    log.startLogging(sys.stdout)
    reactor.listenTCP(port, ProxyFactory())
    reactor.run()

if __name__ == '__main__':
    if sys.argv[1:]:
        run(int(sys.argv[1]))
    else:
        run()
